import { BehaviorSubject, Subscription } from 'rxjs';
import { warn } from 'cc';

/**
 * 自放行循环
 * 
 * 
 * 
        let RSCL = new RxSelfClearanceLoop().init(['a', 'b', 'c', 'd']); // 先按顺序定义好每次循环输入的key
        RSCL.subscribe((key: string) => {
            CCTimer(1).subscribe(_ => { // 此处实现需要的异步方法，例如这里的延时示例
                cc.log('key:', key);
                RSCL.next(); // 在异步完成后，调用next请求下一个key再次做此循环
            });
        }, () => {
            cc.log('complete!'); // 全部完成后，此处有返回
        })

 */
export class RxSelfClearanceLoop<T extends string | number> {

    static Create<T extends string | number>(list: T[]) {
        return new RxSelfClearanceLoop().init(list);
    }

    _subject: BehaviorSubject<{ v: T, self: RxSelfClearanceLoop<T> }> = null;

    _nextRootKeyDic: any = {};
    _lastRootKey: any = null;
    _firstRootKey: any = null;

    init(list: T[]): RxSelfClearanceLoop<T> {

        if (list.length == 0) {
            warn('RxSelfClearanceLoop 输入列表至少需要一个元素');
            return;
        }

        for (let i = 0; i < list.length; i++) {
            let rootKey = list[i];
            if (this._lastRootKey != null) {
                this._nextRootKeyDic[this._lastRootKey] = rootKey;
            } else {
                this._firstRootKey = rootKey;
            }
            this._lastRootKey = rootKey;
        }

        this._subject = new BehaviorSubject<{ v: T, self: RxSelfClearanceLoop<T> }>({ v: list[0], self: this });
        return this;
    }

    subscribe(param: { next: (_: { v: T, self: RxSelfClearanceLoop<T> }) => void, complete?: () => void }): Subscription {
        return this._subject.subscribe({ next: param.next, complete: param.complete });
    }

    next() {
        let curValue = this._subject.value.v;
        let nextValue = this._nextRootKeyDic[curValue];
        if (nextValue == null) {
            this._subject.complete();
        } else {
            this._subject.next({ v: nextValue, self: this });
        }
    }
}